import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger, LogLevel, ValidationPipe } from '@nestjs/common';
import { TransformInterceptor } from './common/interceptor/transform.interceptor';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  // 设置日志级别（生产环境推荐 'log', 'error', 'warn'）
  const logLevels: LogLevel[] =
    process.env.NODE_ENV === 'production'
      ? ['log', 'error', 'warn']
      : ['log', 'error', 'warn', 'debug', 'verbose'];
  const app = await NestFactory.create(AppModule, {
    logger: logLevels,
  });
  app.useGlobalPipes(new ValidationPipe()); // 启用管道
  app.useGlobalInterceptors(new TransformInterceptor());
  const configService = app.get(ConfigService); // 获取配置
  const port = configService.get<number>('PORT') || 3000;
  await app.listen(port);
  const logger = new Logger('Bootstrap');
  logger.log(`🚀 应用正在 ${port} 端口上运行`);
  logger.log(`🌱 环境: ${configService.get('NODE_ENV') || 'development'}`);
  // 捕获退出信号并关闭应用
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
  process.on('SIGINT', async () => {
    await app.close();
    process.exit(0);
  });

  // eslint-disable-next-line @typescript-eslint/no-misused-promises
  process.on('SIGTERM', async () => {
    await app.close();
    process.exit(0);
  });
}
void bootstrap();
